package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Map search(Map<String, String> searchMap)throws Exception {
        Map<String,Object> resultMap=new HashMap<>();
        //判断是否有查询条件
        if (null!=searchMap){//有查询条件
            //组合条件对象
            //动态传入条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //0.如果searchMap.get("keywords")有数据
            if (!StringUtils.isEmpty(searchMap.get("keywords"))){
                boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
            }

            //1.条件.品牌
            if (StringUtils.isNotEmpty(searchMap.get("brand"))){
                //如果品牌表不为空
                boolQueryBuilder.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
                //filter过滤条件
            }


            //2.条件,规格
            for (String key : resultMap.keySet()) {
                //以什么开头
                if (key.startsWith("spec_")){
                    String value = searchMap.get(key).replaceAll("%2B", "+");
                    boolQueryBuilder.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }
            //3.条件,价格
            if (StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
                // 0-500 500-1000
                if (prices.length == 2){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }

            //4.原生搜索实现类
            NativeSearchQueryBuilder nativeSearchQueryBuilder=new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

            //5.高亮显示
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮域
                    .preTags("<span style='color:red'>")//高亮样式的前缀
                    .postTags("</span>");//高亮样式的后缀
            nativeSearchQueryBuilder.withHighlightFields(field);

            //6.品牌聚合查询
            String skuBrand="skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //7.规格聚合查询
            String skuSpec="skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //8.排序
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if ("ASC".equals(searchMap.get("sortRule"))){
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                }else{
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }
            }


            //9.开启分页查询
            String pageNum = searchMap.get("pageNum"); //当前页
            String pageSize = searchMap.get("pageSize"); //每页显示多少条
            if (null==pageNum){
                pageNum="1";
            }
            if (null==pageSize){
                pageSize="30";
            }
            //分页
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));

            //10.执行查询,返回结果对象
            AggregatedPage<SkuInfo> aggregatedPage=elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    List<T> list=new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    if (null!=hits){
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            list.add((T)skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //11.总条数
            resultMap.put("total",aggregatedPage.getTotalElements());
            //12.总页数
            resultMap.put("totalPages",aggregatedPage.getTotalElements());
            //13.查询结果集合
            resultMap.put("rows",aggregatedPage.getContent());
            //14.获取品牌聚合结果
            StringTerms stringTerms= (StringTerms) aggregatedPage.getAggregation(skuBrand);
            List<String> collect = stringTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList",collect);
            //15.获取规格聚合结果
           StringTerms stringTerms1= (StringTerms) aggregatedPage.getAggregation(skuSpec);
            List<String> collect1 = stringTerms1.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",this.formartSpec(collect1));
            //16.返回当前页
            resultMap.put("pageNum",pageNum);
            return resultMap;
        }
        return null;
    }

    public Map<String,Set<String>> formartSpec(List<String> specList){
        Map<String,Set<String>> resultMap=new HashMap<>();
        if (specList!=null&&specList.size()>0){
            for (String  specJsonString: specList) {
                //将json数据转换成map
                Map<String,String> specMap = JSON.parseObject(specJsonString, Map.class);
                for (String specKey : specMap.keySet()) {
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet==null){
                        specSet=new HashSet<String>();
                    }
                    //将规格的值放入set中
                    specSet.add(specMap.get(specKey));
                    //将set的值放入map中
                    resultMap.put(specKey,specSet);
                }
            }
        }
        return resultMap;
    }


}
